<?php
namespace Home\Controller;
use Common\Model\OrderModel;
use Home\Event\LetterEvent;
use Home\Event\WeixinEvent;
use Think\Controller;
use Think\Model;

//set_time_limit(100);

class TasksController extends Controller {

    public function task(){

        //闪购定时任务0:00执行  把未卖完 的返回库存
        $timeOut = $this->isSgTimeOut();
        if(!empty($timeOut)){
            //返回 剩余未购买库存
            $db = new Model();
            $textname = $_SERVER['DOCUMENT_ROOT']."/Datalog/sg/".date('Y-m-d')."sgLog.txt";
            $textnamefail = $_SERVER['DOCUMENT_ROOT']."/Datalog/sg/"."sgLogDefail.txt";
            foreach ($timeOut as $k=>$value){

                $db->startTrans();

                $new_freez = M('b2c_store_product')->where(['store_pid'=>$value['store_pid']])->find()['freez'];

               if($value['initnum']> $new_freez){
                   $content = date('Y-m-d H:i:s').' store_pid:'.$value['store_pid'].',sg_goods 主ID: '.$value['id'].',库存异常，冻结库存小于了闪购'.$value['initnum'].'剩余库存';
                   $failchage = M('starbuy_flashsales_goods')->where(['id'=>$value['id']])->save(['is_task'=>1,'is_fail'=>1]);
                   if($failchage !== false){
                       $db->commit();
                       $this->addText($textnamefail,$content);
                   }else{
                       $db->rollback();
                   }
                   continue;
               }
                $res = M('b2c_store_product')->where(['store_pid'=>$value['store_pid']])->setDec('freez',$value['initnum']);

                $rulchage = M('starbuy_flashsales_goods')->where(['id'=>$value['id']])->save(['is_task'=>1,'is_back_num'=>$value['initnum']]);
                $content = date('Y-m-d H:i:s').' store_pid:'.$value['store_pid'].',sg_goods 主ID: '.$value['id'].',闪购返回'.$value['initnum'].'库存';

                //写入text文档
                if($res !== false && $rulchage !== false && $res !== false){
                    $db->commit();
                    $this->addText($textname,$content);
                }else{
                    $content_fail = date('Y-m-d H:i:s').' store_pid:'.$value['store_pid'].',sg_goods 主ID: '.$value['id'].',闪购返回'.$value['initnum'].'库存失败';
                    $this->addText($textnamefail,$content_fail);
                    $db->rollback();
                }

            }
        }

        //未支付 订单 定时任务
        $orderList = $this->isOrderNopay();
        if(!empty($orderList)){

            $db_order = new Model();

            $OrdernameTxt = $_SERVER['DOCUMENT_ROOT']."/Datalog/order/".date('Y-m-d')."OrderLog.txt";
            $OrdernameTxtfail = $_SERVER['DOCUMENT_ROOT']."/Datalog/order/"."OrderLogDefail.txt";
            foreach ($orderList as $ko=>$v){
                //返回库存
                foreach ($v as $item){


                    $new_freez = M('b2c_store_product')->where(['store_pid'=>$item['store_pid']])->find()['freez'];

                    //判断是否库存异常
                    if($item['nums'] > $new_freez ){
                        $content_order = date('Y-m-d H:i:s').' 订单ID:'.$item['order_id'].' 店铺商品sp_id:'.$item['store_pid'].',库存异常，冻结库存小于了订单商品购买量'.$item['nums'];
                        $isfail_cancel = M('b2c_orders')->where(['order_id'=>$item['order_id']])->save(['is_timing_fail'=>'1']);
                        if($isfail_cancel !== false){
                            $this->addText($OrdernameTxtfail,$content_order);
                        }
                        continue;
                    }
                    //返回库存
                    $spRes = M('b2c_store_product')->where(['store_pid'=>$item['store_pid']])->setDec('freez',$item['nums']);
                    $content_order_items = date('Y-m-d H:i:s').' 订单ID:'.$item['order_id'].' 店铺商品sp_id:'.$item['store_pid'].',客户下单超过24小时未支付，作废订单,返回'.$item['nums'].'冻结库存';

                    if($spRes !== false ){
                        $this->addText($OrdernameTxt,$content_order_items);
                    }

                }

                //开启事务
                $db_order->startTrans();
                //操作订单
                $oModle =  new OrderModel();
                //如果客户有使用优惠券 返回使用优惠卷
                if(!empty($v[0]['coupon_id'])){
                    $save5 = $oModle->isBackCoupon(3, $ko, 0, 1);
                    if($save5['status']==0){
                        $content_order_coupon1 = date('Y-m-d H:i:s').' 订单ID:'.$ko.',返回该订单使用优惠卷失败';
                        $this->addText($OrdernameTxtfail,$content_order_coupon1);
                    }else{
                        $content_order_coupon = date('Y-m-d H:i:s').' 订单ID:'.$ko.',返回该订单使用优惠卷成功';
                        $this->addText($OrdernameTxt,$content_order_coupon);
                    }

                }
                $isOk = M('b2c_orders')->where(['order_id'=>$ko])->save(['status'=>'dead','order_msg'=>'订单失效']);

                $content_order = date('Y-m-d H:i:s').' 订单ID:'.$ko.',客户下单超过24小时未支付，作废订单';

                // 系统取消订单日志记录
                $order_log = M('b2c_order_log')->add([
                    'rel_id' => $ko,
                    'op_name' => '系统',
                    'alttime' => time(),
                    'behavior' => 'cancel',
                    'result' => 'SUCCESS',
                    'log_text' => '系统取消未支付订单',
                ]);



                /***********************5-20**取消订单，返回奖金***********************/

                $order_data =  M('b2c_orders')->where(['order_id'=>$ko])->find();
                if($order_data['bonus_pay']>0){

                    //返回奖金，并记录日志
                    $old_money = M('distribution_member')->where(['local_id'=>$order_data['local_id'],'member_id'=>$order_data['member_id']])->find()['current_bonus'];
                    $new_money = $old_money + $order_data['bonus_pay'];
                    $res_dm =  M('distribution_member')->where(['local_id'=>$order_data['local_id'],'member_id'=>$order_data['member_id']])->save(['current_bonus'=>$new_money]);
                    if($res_dm === false){
                        $this->addText($OrdernameTxtfail,'订单号：'.$ko.'返回奖金失败!');
                    }
                    $is_add_dm_log = M('b2c_bonus_log')->add([
                        'local_id'=>$order_data['local_id'],
                        'member_id'=>$this->member_id,
                        'type'=>'0',
                        'change'=>'8',
                        'change_num'=>$order_data['bonus_pay'],
                        'param'=>$order_data['order_id'].','.$order_data['bonus_pay'],
                        'time'=>time(),
                        'msg'=>'取消订单，返回使用奖金',
                    ]);

                    if($is_add_dm_log === false){
                        $this->addText($OrdernameTxtfail,'订单号：'.$ko.'添加返回奖金日志失败!');
                    }
                }
                /****************************************************/

                if($order_log !== false && $isOk !== false){
                    $this->addText($OrdernameTxt,$content_order);
                    $db_order->commit();
                }else{
                    $content_order_fail = date('Y-m-d H:i:s').' 订单ID:'.$ko.',客户下单超过24小时未支付，作废订单失败';
                    $this->addText($OrdernameTxtfail,$content_order_fail);
                    $db_order->rollback();
                }
            }

        }
        //定时任务 自动确认收货  的订单信息
         $suer_order = $this->isSureOrder();
         if(!empty($suer_order)){

             $sureOrdernameTxt = $_SERVER['DOCUMENT_ROOT']."/Datalog/sureorder/".date('Y-m-d')."OrderLog.txt";
             $sureOrdernameTxtfail = $_SERVER['DOCUMENT_ROOT']."/Datalog/sureorder/"."OrderLogDefail.txt";
             $db_sureorder = new Model();
             foreach ($suer_order as $kk=>$vv){
                 //开启事务
                 $db_sureorder->startTrans();

                 $result = M('b2c_orders')->where(['order_id'=>$vv['order_id'],'local_id'=>$vv['local_id']])->save(['received_status'=>'1','comment_status'=>'1','order_msg'=>'待评价','received_time'=>time()]);


                 $ok_msg = '订单发货7天系统自动确认收货';
                 // 系统订单确认收货日志记录
                 $ordersure_log = M('b2c_order_log')->add([
                     'rel_id' => $vv['order_id'],
                     'op_name' => '系统',
                     'alttime' => time(),
                     'behavior' => 'receive',
                     'result' => 'SUCCESS',
                     'log_text' => $ok_msg,
                 ]);

                 $isc = M('b2c_order_delivery_time')->where(['order_id'=>$vv['order_id']])->save(['is_task'=>1]);
                 if($result !== false && $ordersure_log !== false && $isc !== false){
                     $content_order = date('Y-m-d H:i:s').' 订单ID:'.$vv['order_id'].'发货超过7天系统自动确认收货';
                     $this->addText($sureOrdernameTxt,$content_order);
                     $db_sureorder->commit();
                 }else{
                     $content_order_fail = date('Y-m-d H:i:s').' 订单ID:'.$vv['order_id'].'发货超过7天系统自动确认收货失败';
                     $this->addText($sureOrdernameTxtfail,$content_order_fail);
                     $db_sureorder->rollback();
                 }



             }

         }

         //定时任务 完结订单
         $over_order = $this->isOverOrder();
         if(!empty($over_order)){
             $over_orderTxt = $_SERVER['DOCUMENT_ROOT']."/Datalog/orderFinish/".date('Y-m-d')."OrderLog.txt";
             $over_orderTxtfail = $_SERVER['DOCUMENT_ROOT']."/Datalog/orderFinish/"."OrderLogDefail.txt";
             $db_over_order = new Model();

             foreach ($over_order as $kk1=>$vv1){

              //开启事务
              $db_over_order->startTrans();
              $results = M('b2c_orders')->where(['order_id'=>$vv1['order_id'],'local_id'=>$vv1['local_id']])->save(['order_msg'=>'订单完结','status'=>'finish']);

              $isc_finish = M('b2c_order_delivery_time')->where(['order_id'=>$vv1['order_id']])->save(['is_task'=>2]);
              $isFinishMsg = '订单发货14天系统自动完结订单';

                 // 系统订单确认收货日志记录
                 $order_finish_log = M('b2c_order_log')->add([
                     'rel_id' => $vv1['order_id'],
                     'op_name' => '系统',
                     'alttime' => time(),
                     'behavior' => 'finish',
                     'result' => 'SUCCESS',
                     'log_text' => $isFinishMsg,
                 ]);

                 // 订单完结给上级提成
                 $orderFinishBonus = orderFinishBonus($vv1);

                 if($results !== false && $order_finish_log !== false && $isc_finish !== false && $orderFinishBonus !== false){
                     $content__finish_order = date('Y-m-d H:i:s').' 订单ID:'.$vv1['order_id'].'发货超过14天系统自动完结订单';
                     $this->addText($over_orderTxt,$content__finish_order);
                     $db_over_order->commit();
                 }else{
                     $content_finish_orderfail = date('Y-m-d H:i:s').' 订单ID:'.$vv1['order_id'].'发货超过14天系统自动完结订单失败';
                     $this->addText($over_orderTxtfail,$content_finish_orderfail);
                     $db_over_order->rollback();
                 }

                 // 订单完结推送消息
                 if (!empty($orderFinishBonus[0])) {
                     WeixinOrderOver($orderFinishBonus[0], $orderFinishBonus[1], $orderFinishBonus[2], $orderFinishBonus[3], $orderFinishBonus[4], $orderFinishBonus[5]);
                 }

             }



         }

    }
    /**
     * @return mixed 定时任务跑到时间了自动确认 的订单详情
     * 冉 3-9 排位申请售后的订单
     */
    public function isSureOrder(){
        $task_order = M('b2c_order_delivery_time dt')
            ->join('left join '.C('DB_PREFIX').'b2c_orders o on o.order_id=dt.order_id')
       ->where(['dt.is_task'=>['neq',2],'o.pay_status'=>'1','o.ship_status' => '1','o.received_status' => '0','o.status' => 'active','dt.delivery_time'=>['lt',time()]])->select();

        /*冉 3-9 排除已发货中，售后订单，自动确认收货*/
        foreach ($task_order as $k=>$value){
           $res = M('b2c_refund_money')->where(['status'=>['not in',['0','5','6','7']],'order_id'=>$value['order_id']])->order('id desc')->find();
           if(!empty($res)){
                unset($task_order[$k]);
           }
        }
        /***********************/
        return $task_order;
    }
    /**
     * @return mixed 定时任务自动完结订单详情
     * 冉 3-9 排位申请售后的订单
     */
    public function isOverOrder(){
        $finish_order = M('b2c_order_delivery_time dt')
            ->join('left join '.C('DB_PREFIX').'b2c_orders o on o.order_id=dt.order_id')
            ->where(['dt.is_task'=>1,'o.pay_status'=>'1','o.ship_status' => '1','o.received_status' => '1','o.status' => 'active','dt.finish_time'=>['lt',time()]])->select();
        /*冉 3-9 排除已发货中，售后订单，自动确认收货*/
        foreach ($finish_order as $k=>$value){
            $res = M('b2c_refund_money')->where(['status'=>['not in',['0','5','6','7']],'order_id'=>$value['order_id']])->order('id desc')->find();
            if(!empty($res)){
                unset($finish_order[$k]);
            }
        }
        /***********************/
        return $finish_order;
    }

    /*
     *闪购过期商品（扫描is_task = 0,initnum !=0）
     */

    public function isSgTimeOut(){
        $info = M('starbuy_flashsales_goods')
            ->alias('a')
            ->join('left join '.C('DB_PREFIX').'starbuy_flashsales_time b on a.tid=b.tid')
            ->join('left join '.C('DB_PREFIX').'b2c_store_product sp on sp.store_pid=a.store_pid')
            ->field('a.promotion_price,a.ini_y_tnum,a.initnum,a.repertory_num,a.countnum,a.store_pid,a.id,b.tid,b.limit,b.begin_time,b.end_time,sp.freez')
            ->where(['a.is_task'=>0,'a.initnum'=>['neq','0'],'b.end_time'=>['lt',time()],'a.is_fail'=>['neq','1']])
            ->select();


        return $info;
    }

    /**
     * @return mixed 未支付的订单
     */
    public function isOrderNopay(){
        $orderInfo = M('b2c_order_items i')
            ->join("left join sdb_b2c_orders  o on o.order_id = i.order_id")
            ->join('left join sdb_b2c_store_product sp on sp.store_pid=i.store_pid')
            ->field('i.nums,i.store_pid,sp.freez,o.order_id,o.coupon_id')
            ->where(['o.status'=>'active','o.pay_status'=>'0','o.createtime'=>['lt',time()-86400],'o.is_timing_fail'=>'0'])
            ->select();
        $tmpArray = array();
        foreach ($orderInfo as $k=>$v){
                $key = $v['order_id'];

                if(array_key_exists($key,$tmpArray)){
                    $tmpArray[$key][] = $v;
                }else{
                    $tmpArray[$key][] = $v;
                }

        }
        return $tmpArray;
    }

    /**
     * @param $filename 文件名
     * @param $content  写入内容
     */
    public function addText($filename,$content){
        $filePath= $filename;
        $handle=fopen($filePath,"a+");

        $str=fwrite($handle,$content."\r\n");

        fclose($handle);
    }

    /**
     * 查看订单状态（如支付修改相应数据）
     */
    public function payStatusQueue(){
        Vendor('WeixinPay.WxPayment');
        $WxPay_obj = new \WxPayment();
        $pay_obj = new PayController();
        $obj = M('b2c_order_num_queue');
        $data = $obj->alias('qu')
            ->join("left join sdb_b2c_order_num  o on o.order_num = qu.order_num")
            ->field('qu.*,o.status')
            ->where(['queue_lock' => 0])
            ->limit(10)
            ->select();
        //dump($data);
        $queueId = '';
        foreach($data as $k1 => $v1){
            if($v1['status'] != 1){
                $r_data = $WxPay_obj->orderQuery($v1['order_num']);
                //dump($r_data);die;
                if($r_data['trade_state'] == 'SUCCESS'){

                    //查询order_num
                    $order_data = M('b2c_orders')->where(['order_num' => $v1['order_num']])->select();
                    if(!$data){
                        //  入日志表
                        $log_data = ['order_id' => $v1['order_num'],'alttime' => time(),'log_type' => 'failure','order_type'=>2,'log_text' => '支付订单号不存在！'];
                        $pay_obj -> orderPayLog($log_data);
                        continue;
                    }

                    //判断是否锁定，锁定说明正在被其它线程处理中或处理完成
                    $model = M();
                    $model->startTrans();
                    try{
                        $nums = $model->query("SELECT * FROM `sdb_b2c_order_num`WHERE order_num='".$v1['order_num']."' LOCK IN SHARE MODE");
                        if($nums){
                            if($nums[0]['status'] == 1){
                                continue;
                            }
                        }
                        foreach($order_data as $k2 => $v2){

                            // 分销
                            $shoppingAward = shoppingAward($v1['member_id'], $v1['local_id'], $v1['order_id']);
                            if ($shoppingAward == false) {
                                throw new Exception(false);
                            }

                            //判断是否已运行过（微信异步时请求时间太短）
                            if($v1['pay_status'] != '1'){
                                $stat = $pay_obj->saveTable($v2,$v1['order_num'],$r_data['transaction_id'],1);
                                if($stat !== true){
                                    throw new Exception($stat);
                                }
                                // 微信支付消息推送给上级会员
                                WeixinPayPushToFatherMember(session('userInfo')['member_id'], $v1['local_id'], $v1['order_id']);
                            }
                        }
                        //修改为已支付
                        $stat_num = M('b2c_order_num ')->where(['order_num' => $v1['order_num']])->save([
                            'transaction_id'=>$r_data['transaction_id'],
                            'pay_money' => $r_data['total_fee']/100,
                            'status' => 1,
                        ]);
                        if($stat_num === false){
                            throw new Exception(false);
                        }
                        $model->commit();
                        $obj->where(['id'=>$v1['id']])->delete();
                    }catch (\Exception $e){
                        $model->rollback();
                        $stat = $e->getMessage();
                        $data = [
                            'rel_id' => $v1['order_num'],
                            'op_id' => '',
                            'alttime' => time(),
                            'behavior' => 'payments',
                            'result' => 'FAILURE',
                        ];
                        // 入日志表
                        if($stat['type'] == 0){
                            $data['log_text'] = '订单号不存在！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 1){
                            $data['log_text'] = '修改订单状态失败！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 2){
                            $data['log_text'] = '添加账目流水失败！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 3){
                            $data['log_text'] = '更新销量失败！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 4){
                            $data['log_text'] = '更新物流受理失败！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 5){
                            $data['log_text'] = '新增会员与店铺关系失败！';
                            $this -> orderLog($data);
                        }
                        if($stat['type'] == 6){
                            $data['log_text'] = '赠送优惠券失败';
                            $this -> orderLog($data);
                        }
                    }
                }
                //echo $obj->_sql();
            }else{
                $obj->where(['id'=>$v1['id']])->delete();
            }

            $queueId .= $v1['id'];
        }
    }

    /**
     * 超过3天提醒
     */
    public function remindShop(){
        $over_orderTxt = $_SERVER['DOCUMENT_ROOT']."/Datalog/orderFinish/".date('Y-m-d')."_remindShop.txt";
        //查询超过3天未发货的订单
        $where = [
            'is_zt'                 => 1,
            'pay_status'            => '1',
            'ship_status'           => '1',
            'received_status'       => '0',
            'last_modified'         => ['ELT',time()-259200],
            'status'                => 'active',
            'refund_front_status'   => ['NEQ','1'],
        ];
        $data = M('b2c_orders')->where($where)->select();
        //echo M()->_sql();
        //dump($data);die;
        //echo M()->_sql();die;
        foreach($data as $k1 => $v1){
            //查询会员信息
            $member_data = M('b2c_members')->where(['member_id' => $v1['member_id']])->find();
            if(!$member_data){
                $msg = date('Y-m-d H:i:s').' 订单ID:'.$v1['order_id'].'会员ID：'.$v1['member_id'].'会员信息不存在！';
                $this->addText($over_orderTxt,$msg);
            }
            //短信
            $mobile = $member_data['mobile'];
            $content = '亲，您的自提宝贝已经等你3天了，请尽快到自提点自助提货哟！';
            $letter_obj = new LetterEvent();
            $status = $letter_obj->sendLetter($mobile,$content);
            if($status['status'] !== true){
                $msg = date('Y-m-d H:i:s').' 订单ID:'.$v1['order_id'].'会员ID：'.$v1['member_id'].'短信发送失败！'.
                    '返回码：'.$status['status'].'；返回消息：'.$status['msg'];
                $this->addText($over_orderTxt,$msg);
            }
            //微信推送
            $muban = M('wx_information')->where(['is_type' => 1,'is_terrace' => 1]) ->find();
            $cs = array(
                'touser'=>$member_data['openid'],
                'template_id'=>trim($muban['template_id']),
                'url'=>'',
                'data'=>[
                    'first'=>[
                        'value'=>'亲，您购买的宝贝已在自提点等你3天了~',
                        'color'=>"#173177",
                    ],
                    "keyword1"=>[
                        "value"=>$v1['order_id'],
                        "color"=>"#173177",
                    ],
                    "keyword2"=>[
                        "value"=>date('Y-m-d H:i:s',$v1['last_modified']),
                        "color"=>"#173177",
                    ],
                    "keyword3"=>[
                        "value"=>'可以提货',
                        "color"=>"#173177",
                    ],
                    "keyword4"=>[
                        "value"=>$v1['zT_addr'],
                        "color"=>"#173177",
                    ],
                    "remark"=>[
                        "value"=>"请尽快到自提点自助提货，谢谢您的配合哦！",
                        "color"=>"#173177",
                    ],
                ],
            );
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
            $obj = new WeixinEvent();
            $msg = $obj->parameterPostBtn($cs,$url,1);
            if($msg['errcode'] != 0){
                $msg = date('Y-m-d H:i:s').' 订单ID:'.$v1['order_id'].'会员ID：'.$v1['member_id'].'微信推送失败！'.
                    '返回码：'.$msg['errcode'].'；返回消息：'.$msg['errmsg'];
                $this->addText($over_orderTxt,$msg);
            }
        }
        //echo 111;
    }

}